import redis


class RDBTool(object):
    """
    RDB操作工具
    """
    # 连接池对象
    sr = None  # RedisPool
    app = None

    @classmethod
    def init_app(cls, app=None):
        if not app:
            raise Exception("app无效")
        cls.app = app
        cls.app.rdb = cls
        if cls.sr is None:
            cls.sr = cls._init_pool(app)

    @classmethod
    def _init_pool(cls, app):
        config = app.config.copy()
        config = cls._set_default(config)
        return redis.StrictRedis(host=config['RDB_HOST'], port=config['RDB_PORT'], password=config['RDB_PWD'],
                                 encoding=config["RDB_CHARSET"], db=config["RDB_DB"], decode_responses=True)

    @classmethod
    def from_object(cls, obj):
        if cls.sr is not None:
            return
        config = dict()
        for key in dir(obj):
            if key.isupper():
                config[key] = getattr(obj, key)
        config = cls._set_default(config)
        cls.sr = redis.StrictRedis(host=config['RDB_HOST'], port=config['RDB_PORT'], password=config['RDB_PWD'],
                                   encoding=config["RDB_CHARSET"], db=config["RDB_DB"], decode_responses=True)

    @classmethod
    def _set_default(cls, config):
        config.setdefault('RDB_HOST', '127.0.0.1')
        config.setdefault('RDB_PORT', 3306)
        config.setdefault('RDB_PASSWORD', None)
        config.setdefault('RDB_DB', 0)
        config.setdefault('RDB_CHARSET', 'utf-8')  # 数据库连接编码
        return config

    @classmethod
    def from_object(cls, obj):
        if cls.sr is not None:
            return
        config = dict()
        for key in dir(obj):
            if key.isupper():
                config[key] = getattr(obj, key)
        config = cls._set_default(config)
        cls.sr = redis.StrictRedis(host=config['RDB_HOST'], port=config['RDB_PORT'], password=config['RDB_PWD'],
                                   encoding=config["RDB_CHARSET"], db=config["RDB_DB"], decode_responses=True)

    @classmethod
    def set(cls, name, value, ex=None, px=None, nx=False, xx=False, *args, **kwargs):
        return cls.sr.set(name=name, value=value, ex=ex, px=px, nx=nx, xx=xx, *args, **kwargs)

    @classmethod
    def get(cls, name):
        return cls.sr.get(name=name)

    @classmethod
    def delete(cls, names):
        return cls.sr.delete(names)

    @classmethod
    def incr(cls, name, amount=1):
        return cls.sr.incr(name, amount)

    @classmethod
    def lock(cls, name, timeout=None, sleep=0.1, blocking_timeout=None, lock_class=None, thread_local=True):
        """
                Return a new Lock object using key ``name`` that mimics
                the behavior of threading.Lock.

                If specified, ``timeout`` indicates a maximum life for the lock.
                By default, it will remain locked until release() is called.

                ``sleep`` indicates the amount of time to sleep per loop iteration
                when the lock is in blocking mode and another client is currently
                holding the lock.

                ``blocking_timeout`` indicates the maximum amount of time in seconds to
                spend trying to acquire the lock. A value of ``None`` indicates
                continue trying forever. ``blocking_timeout`` can be specified as a
                float or integer, both representing the number of seconds to wait.

                ``lock_class`` forces the specified lock implementation.

                ``thread_local`` indicates whether the lock token is placed in
                thread-local storage. By default, the token is placed in thread local
                storage so that a thread only sees its token, not a token set by
                another thread. Consider the following timeline:

                    time: 0, thread-1 acquires `my-lock`, with a timeout of 5 seconds.
                             thread-1 sets the token to "abc"
                    time: 1, thread-2 blocks trying to acquire `my-lock` using the
                             Lock instance.
                    time: 5, thread-1 has not yet completed. redis expires the lock
                             key.
                    time: 5, thread-2 acquired `my-lock` now that it's available.
                             thread-2 sets the token to "xyz"
                    time: 6, thread-1 finishes its work and calls release(). if the
                             token is *not* stored in thread local storage, then
                             thread-1 would see the token value as "xyz" and would be
                             able to successfully release the thread-2's lock.

                In some use cases it's necessary to disable thread local storage. For
                example, if you have code where one thread acquires a lock and passes
                that lock instance to a worker thread to release later. If thread
                local storage isn't disabled in this case, the worker thread won't see
                the token set by the thread that acquired the lock. Our assumption
                is that these cases aren't common and as such default to using
                thread local storage.        """
        return cls.sr.lock(name, timeout, sleep, blocking_timeout, lock_class, thread_local)
